//----------------------------------Include-------------------------------------
#include "mcu.h"
#include "glbvar.h"
//------------------------------------------------------------------------------

//APB1 : TIM3, TIM6, LPTIM
//APB2 : TIM1, TIM8

//-----------------------------------Macro--------------------------------------
#define _TIM_INST     TIM3
#define _IRQn         TIM3_IRQn
//------------------------------------------------------------------------------

//--------------------------------Static Var------------------------------------
static uint32_t    src_clk;
static uint32_t    clk_div;
static uint32_t    req_freqHz;
static uint32_t    period_cnt;
//------------------------------------------------------------------------------

//--------------------------------Public Func-----------------------------------
void mcu_init_tim3(void)
{
//periph clock
  RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_TIM3, ENABLE);
  
//timer base
  src_clk    = mcu_get_clk_pclk1();
  clk_div    = 1000;
  req_freqHz = 10;       //Hz
  period_cnt = (src_clk/clk_div)/req_freqHz;
  
  TIM_TimeBaseInitType    TIM_TimeBaseS;
  TIM_InitTimBaseStruct (&TIM_TimeBaseS);
  
  TIM_TimeBaseS.Prescaler = clk_div -1;
  TIM_TimeBaseS.CntMode   = TIM_CNT_MODE_UP;
  TIM_TimeBaseS.Period    = period_cnt -1;
  TIM_TimeBaseS.ClkDiv    = 0;
  TIM_TimeBaseS.RepetCnt  = 0;
  TIM_InitTimeBase(_TIM_INST, &TIM_TimeBaseS);
  
  TIM_SelectOutputTrig(_TIM_INST, TIM_TRGO_SRC_UPDATE); //use UPDATE for trigger out
  
#if 0
//interrupt
  TIM_ConfigInt(_TIM_INST, TIM_INT_UPDATE, ENABLE);
//NVIC
  NVIC_InitType   NVIC_InitS;
  NVIC_InitS.NVIC_IRQChannel         = _IRQn;
  NVIC_InitS.NVIC_IRQChannelPriority = 2;
  NVIC_InitS.NVIC_IRQChannelCmd      = ENABLE;
  NVIC_Init(&NVIC_InitS);
#endif

//enable
  TIM_Enable(_TIM_INST, ENABLE);
}
//------------------------------------ISR---------------------------------------
void TIM3_IRQHandler(void)
{
  if(_TIM_INST->STS &  (1<<0)){
    _TIM_INST->STS &= ~(1<<0);
    
#if 0
    static unsigned int cnt;
    if(++cnt >= 100){
      cnt = 0;
      mcu_led_toggle();
    }
#endif
  }
  
  if(_TIM_INST->STS){
    _TIM_INST->STS = 0;
  }
}
//------------------------------------EOF---------------------------------------




